const express = require('express');
const router = express.Router();
const utils = require('../../utils');

const filters = [
    {
        Name: '名称',
        Type: 'String',
    },
    {
        Name: '详情',
        Type: 'String',
    },
    {
        Name: '类型',
        Type: 'String',
    },
];

// announcement
router.get('/',
    (req, res, next) => {
        // query
        res.locals.filter = Object.assign(
            {}, 
            res.app.modules['input-field'].generateQueryFilter(filters, req.query), 
            res.locals.filter, 
            utils.makeQueryFilters(req, 'announcement'),
            { Status: '1', Deleted: false, Freeze: { $exists: false, $ne: true } }
        );

        res.locals.fields = [
            'id',
            'LastUpdateDate',
            
            '名称',
            '图片',
            '详情',
            '类型',
            '时间',
        ];
        res.locals.options = {
            sort: { 推荐指数: 'desc', 时间: 'desc', LastUpdateDate: 'desc' },
            lean: true
        };

        return next();
    },
    router.FindDocuments('announcement', false, async (req, res) => {
        if(!res.locals.data || !res.locals.data.total) return;

        for (let i = 0; i < res.locals.data.docs.length; i += 1) {
            const doc = res.locals.data.docs[i];

            doc.详情 = utils.repalceHtmlToText(doc.详情 || '');
            doc.日期 = doc.时间 || doc.LastUpdateDate;
            delete doc.LastUpdateDate;

            await utils.getDictLabel(req, res, '类型', '公告类型');
        }
    })
);

// announcement details
router.get('/:id',
    (req, res, next) => {
        res.locals.filter = { id: req.params.id, Status: '1', Deleted: false, Freeze: { $exists: false, $ne: true } };
        res.locals.fields = [
            'id',
            'LastUpdateDate',
            '推荐指数',
            '日期',
            
            '名称',
            '图片',
            '详情',
            '类型',
        ];
        res.locals.options = {
            lean: true
        };

        return next();
    },
    router.FindDocuments('announcement', false, async (req, res) => {
        if(res.locals.data && res.locals.data.total) {
            res.locals.data = res.locals.data.docs[0];
            await utils.getDictLabel(req, res, '类型', '公告类型');
        } else {
            res.locals.data = {};
        }
    }),
);

module.exports = router;
